import time
import random
import hashlib  # hash加密的模块

import requests


class YoudaoFanyiSpider:
    def __init__(self):
        self.headers = {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive',
            'Content-Length': '328',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Cookie': 'OUTFOX_SEARCH_USER_ID=-862001122@10.169.0.102; JSESSIONID=aaaKsuqQs6Q59__U72XVx; OUTFOX_SEARCH_USER_ID_NCOO=2116978189.1472313; ___rl__test__cookies=1631858969201',
            'Host': 'fanyi.youdao.com',
            'Origin': 'https://fanyi.youdao.com',
            'Referer': 'https://fanyi.youdao.com/',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
            'X-Requested-With': 'XMLHttpRequest'
        }
        self.url = 'https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

    def get_data(self, word):
        hash = hashlib.md5()
        hash.update(
            '5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'.encode())
        t = hash.hexdigest()
        r = str(int(time.time()*1000))
        i = r + str(random.randint(0, 9))
        hash2 = hashlib.md5()
        s = "fanyideskweb" + word + i + "Y2FYu%TNSbMCxc3t2u^XT"
        hash2.update(s.encode())
        sign = hash2.hexdigest()
        data = {
            'i': word,
            'from': 'AUTO',
            'to': 'AUTO',
            'smartresult': 'dict',
            'client': 'fanyideskweb',
            'salt': i,  # '16318589692033',
            'sign': sign,  # 'fedcd799e4399458c7328027fd56b8a7',
            'lts': r,  # '1631858969203',
            'bv': t,
            'doctype': 'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_CLICKBUTTION',
        }
        return data


    def translate(self, word):
        data = self.get_data(word)
        resp = requests.post(
            self.url,
            headers=self.headers,
            data=data
        )
        r = resp.json()
        return r['translateResult'][0][0]['tgt']


if __name__ == '__main__':
    while True:
        word = input('请输入翻译的文字:')
        spider = YoudaoFanyiSpider()
        if word == 'quit':
            break
        trans = spider.translate(word)
        print(trans)